package cn.vc.auth.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.vc.auth.entity.po.VUser;
import cn.vc.auth.util.SecurityUtil;
import cn.vc.basicmodule.rabbitmqconfig.ShopRabbitMqConfig;
import cn.vc.basicmodule.entity.Result;
import cn.vc.auth.service.CaptchaService;
import cn.vc.auth.service.UserService;
import cn.vc.wallet.feign.clients.WalletClient;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 用户服务接口
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    private final UserService userService;
    private final CaptchaService captchaService;

    private final AmqpTemplate amqpTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private HttpSession session;
    @Resource
    private HttpServletRequest request;
    @Autowired
    public WalletClient walletClient;
    private static final Long memberMonthPrice = 300L;



    @Autowired
    public UserController(UserService userService, CaptchaService captchaService, AmqpTemplate amqpTemplate) {
        this.userService = userService;
        this.captchaService =captchaService;
        this.amqpTemplate = amqpTemplate;
    }



    /**
     * 上传头像
     * @return
     */
//    @PostMapping("/uploadAvatar")
//    public Result<?> uploadAvatar(@RequestHeader("token") String token, @RequestBody MultipartFile file) throws IOException {
//        VUser VUser = userService.selectByToken(token);
//
//        MultipartFile avatarImg = file;
//        File file1 = new File("./UserService/src/main/resources/static/userstatic/avatar/"+ VUser.getId()+"/");
//        if (file1.exists()) {
//            System.out.println("文件夹已经存在");
//        } else {
//            file1.mkdirs();
//            System.out.println("创建文件夹");
//        }
//        //文件名
//        String name = avatarImg.getName();
//        //文件类型 content-type: "image/png",
//        String type = avatarImg.getContentType();
//        //文件大小
//        long size = avatarImg.getSize();
//        //文件路径  位置 + 文件名
//        String filePath = "C:/Users/mo/Desktop/VC/UserService/src/main/resources/static/userstatic/avatar/" + VUser.getId() +"/" + name;
//        File saveFile = new File(filePath);
//        avatarImg.transferTo(saveFile);        // 文件保存
//
//        VUser.setAvatarUrl("/userstatic/avatar/"+ VUser.getId()+"/"+name);
//        userService.updateAvatarUrl(VUser);
//
//        return new Result<>();
//    }

    /**
     * 实名认证
     * @param captcha
     * @param name
     * @param idNum
     * @return
     */
    @PostMapping("/1")
    public Result<VUser> realNameAuthentication(@RequestParam("captcha") String captcha, @RequestParam("name") String name, @RequestParam("idNum") String idNum) {
        VUser myVUser = (VUser) session.getAttribute("myUser");
        boolean bo = captchaService.comparisonCaptcha(CaptchaService.prefixType.updateUser.getValue()+"_"+ myVUser.getEmail(), captcha);
        // 1、验证码不同
        // 2、身份证格式错误（前17位必须为数字，最后一位只能是数字或者字母X）
        // 3、不为空，说明已经实名认证，需要修改实名认证，不可直接进行实名认证
        if (!bo || !idNum.matches("\\d{17}[\\dX]") || myVUser.getName()!=null|| myVUser.getIdNum()!=null) return new Result<>(0);
        bo = userService.updateNameAndIdNum(myVUser.getId(), name, idNum);
        return new Result<>(bo);
    }
    /**
     * <h2>蓝V认证</h2>
     * @return
     */
    @PostMapping("/2")
    public Result<?> blueVAuthentication() {
        VUser myVUser = (VUser) session.getAttribute("myUser");
        amqpTemplate.convertAndSend(ShopRabbitMqConfig.Background_BlueV, myVUser.getId());
        return new Result<>(1, "认证已提交至审核！");
    }



    /**
     * <h2>注销用户</h2>
     * @param username
     * @param account
     * @param password
     * @param email
     * @param captcha
     * @return
     */
    @DeleteMapping
    public Result<?> signOut(@RequestParam("username") String username, @RequestParam("account") String account, @RequestParam("password") String password, @RequestParam("email") String email, @RequestParam("captcha") String captcha) {
        boolean bo = captchaService.comparisonCaptcha(CaptchaService.prefixType.deleteUser.getValue()+"_"+email, captcha);
        if (bo) {
            VUser VUser = userService.selectByUsernameAndAccountAndPasswordAndEmail(username, account, password, email);
            if (VUser ==null) return new Result<>(0);
            else {
                bo = userService.deleteById(VUser.getId());
                return new Result<>(bo);
            }
        } else return new Result<>(0);
    }



    /**
     * <h2>查询用户</h2>
     * @return
     */
    @GetMapping
    public Result<VUser> selectUser() {
        try {
            long loginIdAsLong = StpUtil.getLoginIdAsLong();
            VUser user = userService.selectById(loginIdAsLong, false);
            log.info("查询用户 -> "+ user);
            return new Result<VUser>(user != null?1:0, user);
        } catch (NotLoginException e) {
            // StpUtil.getLoginIdAsLong() 抛出异常，说明未登录
            return new Result<>(0);
        }
//        VUser vUser = SecurityUtil.getUser();
//        if (vUser==null) return new Result<>(0);
//        VUser user = userService.selectById(vUser.getId(), false);
//        log.info("查询用户 -> "+ vUser);
//        return new Result<VUser>(user != null?1:0, user);
    }
    /**
     * 查询会员价格
     * @return
     */
    @GetMapping("/member")
    public Long selectMemberPrice() {
        return memberMonthPrice;
    }



    /**
     * 上传头像
     * @return
     */
    @PutMapping("/updateavatar")
//    @PreAuthorize("hasAnyAuthority('ordinary')")
    public Result<?> uploadAvatar(@RequestParam("url") String avatarUrl) throws IOException {
        VUser vUser = SecurityUtil.getUser();
        boolean bo = userService.updateAvatarUrl(vUser.getId(), avatarUrl);
        if (bo) {
            vUser.setAvatarUrl(avatarUrl);
            stringRedisTemplate.opsForValue().set(vUser.getId().toString(), JSON.toJSONString(vUser), 30, TimeUnit.SECONDS);
        }

        return new Result<>(bo);
    }
    /**
     * <h2>修改用户名</h2>
     * @param username 修改后的用户名
     * @return
     */
    @PutMapping("/username")
//    @PreAuthorize("hasAnyAuthority('ordinary')")
    public Result<VUser> updateUsername(@RequestParam String username) {
        VUser myVUser = (VUser) session.getAttribute("myUser");
        boolean bo = userService.updateUsername(myVUser.getAccount(), username);
        return new Result<>(bo?1:0);
    }
    /**
     * <h2>修改密码</h2>
     * @param captcha 验证码
     * @return
     */
    @PutMapping("/password")
//    @PreAuthorize("hasAnyAuthority('ordinary')")
    public Result<VUser> updatePassword(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword, @RequestParam("captcha") String captcha) {
        VUser myVUser = (VUser) session.getAttribute("myUser");
        boolean bo = captchaService.comparisonCaptcha(CaptchaService.prefixType.updateUser.getValue()+"_"+ myVUser.getEmail(), captcha);
        System.out.println(bo);
        if (bo) bo = userService.updatePassword(myVUser.getAccount(), oldPassword, newPassword);
        return new Result<>(bo?1:0);
    }


    /**
     * 购买会员
     * @param months 购买月份
     * @return
     */
    @PutMapping("/member")
//    @PreAuthorize("hasAnyAuthority('ordinary')")
    public Result<?> buyMember(@RequestParam("months") Integer months) {
        VUser myUser = SecurityUtil.getUser();
        if (myUser==null) return Result.NOT_LOGGED_IN();
        // 扣除钻石
        walletClient.diamondDeduction(myUser.getId(), months*memberMonthPrice);
        // 修改会员类型及时长
        userService.butMember(myUser.getId(), 1, months);
        return new Result<>(1);
    }

}
